<template>
  <a-modal :title="title" v-model:visible="modelVisible" :width="800" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formData" :rules="rules" class="managerial-form">
      <div class="form-row">
        <!-- 发票编号 -->
        <a-form-item label="发票编号" name="code" class="form-col">
          <a-input v-model:value="formData.code" disabled />
        </a-form-item>

        <!-- 供应商 -->
        <a-form-item label="供应商" name="supplierId" required class="form-col">
          <a-select v-model:value="formData.supplierId" show-search placeholder="请选择供应商" :options="supplierOptions"
            :loading="supplierLoading" @search="handleSupplierSearch" />
        </a-form-item>
      </div>

      <div class="form-row">
        <!-- 发票类型 -->
        <a-form-item label="发票类型" name="invoiceType" class="form-col">
          <a-select v-model:value="formData.invoiceType" @change="handleInvoiceTypeChange">
            <a-select-option value="1">普通发票</a-select-option>
            <a-select-option value="2">专用发票</a-select-option>
            <a-select-option value="3">农副产品发票</a-select-option>
            <a-select-option value="4">红字专用发票</a-select-option>
            <a-select-option value="5">红字普通发票</a-select-option>
            <a-select-option value="6">红字农副产品发票</a-select-option>
          </a-select>
        </a-form-item>

        <!-- 制单时间 -->
        <a-form-item label="制单时间" name="createTime" class="form-col">
          <a-input v-model:value="formData.createTime" disabled />
        </a-form-item>
      </div>

      <div class="form-row">
        <!-- 采购金额 -->
        <a-form-item label="采购金额" name="amount" required class="form-col">
          <a-input-number v-model:value="formData.amount" :precision="2" style="width: 100%" @change="calculateTax" />
        </a-form-item>

        <!-- 税率 -->
        <a-form-item label="税率" name="taxRate" class="form-col">
          <a-select v-model:value="formData.taxRate" @change="calculateTax">
            <a-select-option :value="0">0%</a-select-option>
            <a-select-option :value="0.13">13%</a-select-option>
            <a-select-option :value="0.17">17%</a-select-option>
          </a-select>
        </a-form-item>
      </div>

      <div class="form-row">
        <!-- 税费 -->
        <a-form-item label="税费" name="tax" class="form-col">
          <a-input-number v-model:value="formData.tax" :precision="2" style="width: 100%" disabled />
        </a-form-item>

        <!-- 核销金额 -->
        <a-form-item label="核销金额" name="writeOffAmount" class="form-col">
          <a-input-number v-model:value="formData.writeOffAmount" :precision="2" style="width: 100%" disabled />
        </a-form-item>
      </div>

      <!-- 发票描述 -->
      <div class="form-row full-width">
        <a-form-item label="发票描述" name="description" class="form-col">
          <a-textarea v-model:value="formData.description" :rows="3" placeholder="请输入发票描述" :maxLength="200"
            show-count />
        </a-form-item>
      </div>

      <!-- 关联单据表格 -->
      <div class="form-row full-width">
        <div class="table-header">
          <div class="title">关联单据</div>
          <div class="buttons">
            <a-button type="primary" :disabled="!formData.supplierId" :icon="h(PlusOutlined)"
              @click="openOrderSelect">选单</a-button>
            <a-button danger :disabled="!selectedRows.length" :icon="h(DeleteOutlined)"
              @click="handleDeleteOrders">删除单</a-button>
          </div>
        </div>
        <vxe-grid ref="relatedGrid" :columns="relatedColumns" :data="relatedOrders" height="200"
          :checkbox-config="{ checkField: 'checked' }" @checkbox-change="handleSelectionChange" />
      </div>
    </a-form>

    <!-- 选单弹窗 -->
    <a-modal v-model:visible="orderSelectVisible" title="选择采购订单" width="1000px" @ok="handleOrderSelectOk">
      <vxe-grid ref="orderGrid" :columns="orderColumns" :data="orderList" height="400" />
    </a-modal>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, h,onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';

export default defineComponent({
  name: 'ManagerialDialog',
  props: {
    visible: Boolean,
    id: String,
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const formRef = ref();
    const modelVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val),
    });
    const title = computed(() => props.id ? '编辑发票' : '新增发票');

    const formData = ref({
      code: '',
      invoiceType: '1', // 默认普通发票
      supplierId: undefined,
      amount: 0,
      taxRate: 0,
      tax: 0,
      creator: '当前用户', // TODO: 从用户状态获取
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      description: '', // 添加发票描述字段
    });

    // 表单验证规则
    const rules = {
      invoiceType: [{ required: true, message: '请选择发票类型' }],
      supplierId: [{ required: true, message: '请选择供应商' }],
      amount: [{ required: true, message: '请输入采购金额' }],
      taxRate: [{ required: true, message: '请选择税率' }],
    };

    // 确认提交
    const handleOk = async () => {
      try {
        await formRef.value?.validate();
        // TODO: 调用保存API
        message.success(props.id ? '修改成功' : '新增成功');
        modelVisible.value = false;
        emit('success');
      } catch (error) {
        console.error('保存失败:', error);
      }
    };

    // 取消
    const handleCancel = () => {
      modelVisible.value = false;
    };

    // 生成发票编号
    const generateInvoiceCode = () => {
      const date = dayjs().format('YYYYMMDD');
      const sequence = '00001'; // TODO: 从后端获取序列号
      return `FP${date}${sequence}`;
    };

    // 税率映射
    const defaultTaxRates = {
      '1': 0,     // 普通发票
      '2': 0.17,  // 专用发票
      '3': 0.13,  // 农副产品发票
      '4': 0,     // 红字专用发票
      '5': 0.17,  // 红字普通发票
      '6': 0.13,  // 红字农副产品发票
    };

    // 发票类型变更
    const handleInvoiceTypeChange = (value: string) => {
      formData.value.taxRate = defaultTaxRates[value];
      calculateTax();
    };

    // 计算税费
    const calculateTax = () => {
      const { amount, taxRate } = formData.value;
      formData.value.tax = Number((amount * taxRate).toFixed(2));
    };

    // 供应商选择相关
    const supplierLoading = ref(false);
    const supplierOptions = ref<any[]>([]);

    const handleSupplierSearch = async (value: string) => {
      if (!value) return;
      supplierLoading.value = true;
      try {
        // TODO: 调用供应商搜索API
        // const res = await supplierApi.search(value);
        // supplierOptions.value = res.data;
      } finally {
        supplierLoading.value = false;
      }
    };

    // 选单相关
    const orderSelectVisible = ref(false);
    const orderList = ref<any[]>([]);
    const orderColumns = [
      { field: 'code', title: '订单编号' },
      { field: 'amount', title: '订单金额' },
      { field: 'createTime', title: '创建时间' },
    ];

    const openOrderSelect = async () => {
      try {
        // TODO: 调用获取未开票订单API
        // const res = await api.getUnbilledOrders(formData.value.supplierId);
        // orderList.value = res.data;
        orderSelectVisible.value = true;
      } catch (error) {
        message.error('获取订单失败');
      }
    };

    // 关联单据表格
    const relatedGrid = ref();
    const relatedOrders = ref<any[]>([]);
    const selectedRows = ref<any[]>([]);

    const relatedColumns = [
      { type: 'checkbox', width: 50 },
      { field: 'voucherNo', title: '凭证编号', width: 180 },
      { field: 'amount', title: '金额', width: 120 }
    ];

    // 处理表格选择变化
    const handleSelectionChange = () => {
      selectedRows.value = relatedGrid.value?.getCheckboxRecords() || [];
    };

    // 删除选中单据
    const handleDeleteOrders = () => {
      if (!selectedRows.value.length) return;

      Modal.confirm({
        title: '确认删除',
        content: '确定要删除选中的单据吗？',
        onOk: () => {
          const selectedIds = selectedRows.value.map(row => row.id);
          relatedOrders.value = relatedOrders.value.filter(order => !selectedIds.includes(order.id));
          selectedRows.value = [];
          // 重新计算金额
          calculateTotalAmount();
        }
      });
    };

    // 计算总金额
    const calculateTotalAmount = () => {
      formData.value.amount = relatedOrders.value.reduce((sum, order) => sum + (order.amount || 0), 0);
      calculateTax();
    };

    // 修改选单确认处理
    const handleOrderSelectOk = () => {
      const selectedOrders = orderGrid.value?.getCheckboxRecords() || [];
      if (selectedOrders.length) {
        // 添加到关联单据表格
        relatedOrders.value = [...relatedOrders.value, ...selectedOrders];
        // 重新计算金额
        calculateTotalAmount();
      }
      orderSelectVisible.value = false;
    };

    // 初始化
    onMounted(() => {
      if (!props.id) {
        formData.value.code = generateInvoiceCode();
      }
    });

    return {
      h,
      formRef,
      formData,
      modelVisible,
      title,
      rules,
      handleOk,
      handleCancel,
      supplierLoading,
      supplierOptions,
      handleSupplierSearch,
      handleInvoiceTypeChange,
      calculateTax,
      PlusOutlined,
      DeleteOutlined,
      orderSelectVisible,
      orderList,
      orderColumns,
      openOrderSelect,
      handleOrderSelectOk,
      relatedGrid,
      relatedOrders,
      relatedColumns,
      selectedRows,
      handleSelectionChange,
      handleDeleteOrders,
    };
  },
});
</script>

<style lang="less" scoped>
.managerial-form {
  padding: 24px;

  .form-row {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;

    &.full-width {
      display: block;

      .form-col {
        :deep(.ant-form-item-control) {
          flex: 1;
        }

        :deep(.ant-input) {
          width: 100%;
        }
      }
    }

    &:last-child {
      margin-bottom: 0;
    }

    .form-col {
      flex: 1;
      margin-bottom: 0;

      :deep(.ant-form-item-label) {
        width: 100px;
        text-align: right;
        padding-right: 8px;
      }

      :deep(.ant-select),
      :deep(.ant-input),
      :deep(.ant-input-number) {
        width: 100%;
      }
    }
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .title {
      font-size: 16px;
      font-weight: 500;
    }

    .buttons {
      display: flex;
      gap: 8px;
    }
  }
}
</style>
